<template>
  <div>
    <el-dialog
      title="加密明文信息"
      :visible.sync="visible"
      @close="$emit('update:show', false)"
      :show="show"
    >
      <el-form :model="form" ref="form">
        <el-form-item label="名称" label-width="80px" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="明文" label-width="80px" prop="ciphertext">
          <el-input
            v-model="form.ciphertext"
            autocomplete="off"
            type="textarea"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="公钥" label-width="80px" prop="pub_key">
          <el-select v-model="form.pub_key" placeholder="请选择公钥">
            <el-option
              v-for="item in key_list"
              :key="item.id"
              :label="item.key_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:show', false)">取 消</el-button>
        <el-button type="primary" @click="encrpytsubmit">加密</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList } from "@/api/key";
import { add } from "@/api/encrypt";
export default {
  data() {
    return {
      visible: this.show,
      key_list: [],
      form: {
        name: "",
        ciphertext: "",
        pub_key: "",
        key: ""
      }
    };
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    fetchData: {
      type: Function,
      default: null
    }
  },
  methods: {
    get_key_data() {
      getList({ page: 1, size: 9999 }).then(res => {
        if (res.code === 200) {
          this.key_list = res.data;
        }
      });
    },
    encrpytsubmit() {
      add(this.form).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$refs["form"].resetFields();
          this.visible = false;
          this.fetchData();
        } else {
          this.$message.error(res.message);
        }
      });
    }
  },
  mounted() {
    this.get_key_data();
  },
  watch: {
    show() {
      this.visible = this.show;
    }
  }
};
</script>
